import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken, getSession, setSession, removeSession } from '@/utils/auth'
import { resetRouter } from '@/router'
import { Message } from 'element-ui'
// import store from '..'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    session: getSession()
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_SESSION: (state, session) => {
    state.session = session
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        const { data } = response.data
        if (response.data.code === 200) {
          commit('SET_SESSION', data.sessionId)
          commit('SET_TOKEN', data.userId)
          setToken(data.userId)
          setSession(data.sessionId)
          resolve(data)
        } else Message.error('登录失败，请检查账号或密码是否正确！')
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { role, username } = response.data.data
        if (!role) {
          return reject('登录失败，请重新登录！')
        }
        const roles = []
        roles.push(role)
        const data = { roles, username }
        commit('SET_NAME', username)
        commit('SET_ROLES', roles)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      removeSession()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

